package com.gs.wechatdemo.audio;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

public class RecordAudioTextView extends AppCompatTextView {

    public RecordAudioTextView(@NonNull Context context) {
        super(context);
    }

    public RecordAudioTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RecordAudioTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            // 手指按下，开始录音
            case MotionEvent.ACTION_DOWN:
                if (onVoiceIVCallBack != null) {
                    onVoiceIVCallBack.onStartRecord();
                }
                return true;
            // 手指移动，判断用户移动位置
            case MotionEvent.ACTION_MOVE:
                if (isCancelled(this, event)) {
                    if (onVoiceIVCallBack != null) {
                        onVoiceIVCallBack.onWillCancelRecord();
                    }
                } else {
                    if (onVoiceIVCallBack != null) {
                        onVoiceIVCallBack.onContinueRecord();
                    }
                }
                return true;
            // 手指抬起，取消录音
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (onVoiceIVCallBack != null) {
                    onVoiceIVCallBack.onStopRecord();
                }
                return true;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 判断手指是否移动到取消录音控件区域
     *
     * @param view
     * @param event
     * @return
     */
    private boolean isCancelled(View view, MotionEvent event) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return event.getRawX() < location[0] ||
                event.getRawX() > location[0] + view.getWidth() ||
                event.getRawY() < location[1] - 40;
    }

    private OnVoiceIVCallBack onVoiceIVCallBack;

    public void setOnVoiceIVCallBack(OnVoiceIVCallBack onVoiceIVCallBack) {
        this.onVoiceIVCallBack = onVoiceIVCallBack;
    }

    public interface OnVoiceIVCallBack {
        /**
         * 开始录音
         */
        void onStartRecord();

        /**
         * 停止录音
         */
        void onStopRecord();

        /**
         * 准备取消录音
         */
        void onWillCancelRecord();

        /**
         * 继续录音
         */
        void onContinueRecord();
    }
}
